const models = require('../db/mysqldb/index')
const { Op } = require("sequelize");

class ChatUserRelationModel {
  /**
   * @description 是否是好友
   * @param {string} user_id
   * @returns
   */
  static async check (user_id, other_user_id) {
    return await models.chat_user_relation.findAll({
      where: {
        user_id,
        other_user_id,
        delete_timestamp: {
          [Op.is]: null,
        },
      },
    })
  }

  /**
   * @description 获取朋友列表
   * @param {string} user_id
   * @returns
   */
  static async findAll (user_id) {
    let sql = `SELECT
      t1.other_user_id as user_id,
      t1.other_user_alias as user_alias,
      su.status,
      su.sex,
      su.avatar,
      su.phone,
      su.realname
    FROM
      chat_user_relation t1 LEFT JOIN sys_user su ON su.user_id = t1.other_user_id 
      WHERE t1.delete_timestamp is NULL and t1.user_id = ${user_id}
    ORDER BY
      CONVERT ( t1.other_user_alias USING gbk ) ASC`
    return await models.sequelize.query(sql, {
      replacements: ['active'],
      type: models.sequelize.QueryTypes.SELECT,
    })
  }

  /**
   * @description 加为好友
   * @param {string} user_id
   * @returns
   */
  static async addRelation (user_id, realname, other_user_id, othername) {
    console.log(user_id, realname, other_user_id, othername);
    return await models.chat_user_relation.bulkCreate([
      {
        user_id,
        other_user_id,
        other_user_alias: othername,
      },
      {
        user_id: other_user_id,
        other_user_id: user_id,
        other_user_alias: realname,
      },
    ])
  }

  /**
   * @description 修改好友备注
   * @param {string} user_id
   * @param {string} other_user_alias
   * @param {string} other_user_id
   * @returns
   */
  static async updateAlias (user_id, other_user_id, other_user_alias) {
    return await models.chat_user_relation.update(
      {
        other_user_alias,
        update_by: user_id,
        update_timestamp: Date.now(),
      },
      {
        where: { user_id, other_user_id },
      }
    )
  }

  /**
   * @description 双向删除好友信息
   * @param {string} user_id
   * @param {string} other_user_id
   * @returns
   */
  static async delete (user_id, other_user_id) {
    let sql = `UPDATE chat_user_relation SET delete_timestamp = ${Date.now()},delete_by = ${user_id}
        WHERE (user_id = ${user_id} and other_user_id = ${other_user_id}) or
         (user_id = ${other_user_id} and other_user_id = ${user_id}) and delete_timestamp is null`
    return await models.sequelize.query(sql)
  }
}
module.exports = {
  ChatUserRelationModel,
}
